﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;//新调用的类所在的命名空间 

namespace vstest1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            

        }



        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //关闭串口 
            
        }
        //send data
        private void button2_Click_1(object sender, EventArgs e)
        {
            string convertdata = textBox3.Text;
            byte[] buffer1 = new byte[1];
            buffer1[0] = Convert.ToByte(convertdata);
            serialPort1.Write(buffer1, 0, 1);
           // MessageBox.Show("数据发送成功", "系统提示");
            
        }
        //form加载的时候就执行，相当于初始化
        private void Form1_Load_1(object sender, EventArgs e)
        {
            serialPort1.Open();
            //增加串口的rx中断处理函数，照抄即可
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
            //从不是创建控件的线程访问它，不加则uart的中断处理函数异常
            CheckForIllegalCrossThreadCalls = false;
        }
        //中断处理函数
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                byte[] data = new byte[serialPort1.BytesToRead];


                serialPort1.Read(data, 0, data.Length);

                foreach (byte Membre in data)
                {
                    string str = Convert.ToString(Membre, 16).ToString();
                    richTextBox1.AppendText(str);
                }

            }
            catch { 
            
            }
        }
    }
 }
